<?php
declare (strict_types = 1);

namespace app\admin\validate;

use think\Validate;

class Category extends Validate {

    protected $rule = [
        "name" => "require",
        "pid" => "require|number|checkPid",
        "id" => "number|checkId",
        "url_key" => "require|checkUrlKey",
        "list_order" => "number",
        "field" => "require|in:name,list_order,url_key,status",
        "val" => "require|checkUpdateVal",
    ];

    protected $message = [
        "name.require" => "分类名称不能为空",
        "pid.require" => "父级分类不能为空",
        "pid.number" => "父级分类参数格式不正确",
        "id.number" => "分类参数格式不正确",
        "url_key.require" => "URL KEY不能为空",
        "url_key.regex" => "URL KEY格式不正确",
        "field.require" => "field参数不能为空",
        "field.in" => "field参数不正确",
        "val.require" => "val参数不能为空",
    ];

    protected $scene = [
        "save" => ["id", "pid", "name", "url_key", "list_order"],
        "update" => ["id", "field", "val"],
        "delete" => ["id"]
    ];


    public function checkId($value, $rule, $data) {
        if (empty($value)) {
            return true;
        }

        $category = (new \app\model\mysql\Category())->find($value);
        if (!$category || $category->id <= 0) {
            return "此分类不存在";
        }

        return true;
    }

    public function checkPid($value, $rule, $data) {
        if ($value === 0) {
            return true;
        }
        $category = (new \app\model\mysql\Category())->find($value);
        if (!$category || $category->id <= 0) {
            return "父级分类不存在";
        }

        return true;
    }

    public function checkUrlKey($value, $rule, $data) {

        if (!$this->regex($value, "^[A-Za-z0-9_\-]+$")) {
            return "URL KEY 格式不正确";
        }
        $currentId = 0;
        if (!isset($data["id"]) || $data["id"] <= 0) {
            $currentId = $data["id"];
        }
        $tmp = \app\model\mysql\Category::checkUrlKey($value, $currentId);
        if ($tmp && $tmp->id > 0) {
            return "此URL KEY已经存在";
        }

        return true;
    }

    public function checkUpdateVal($value, $rule, $data) {
       if ($data["field"] == "url_key") {
           return $this->checkUrlKey($value, $rule, $data);
       }else if ($data["field"] == "list_order" && !is_numeric($value)) {
           return "排序必须为数字";
       }else if ($data["field"] == "status" && !in_array($value, [0, 1])) {
           return "状态参数不正确";
       }

       return true;
    }
}